import 'dart:ui';

import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vamos/core/index.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

/// 发布页面
class VamosPublishInterface extends StatefulWidget {
  final int initialTabIndex;

  const VamosPublishInterface({super.key, this.initialTabIndex = 0});

  @override
  State<VamosPublishInterface> createState() => _VamosPublishInterfaceState();
}

class _VamosPublishInterfaceState extends State<VamosPublishInterface>
    with TickerProviderStateMixin {
  late ReduxQAManager _qaManager;
  late ReduxSocialManager _socialManager;
  late ReduxUserManager _userManager;

  late TabController _tabController;
  final TextEditingController _contentController = TextEditingController();
  final TextEditingController _timeController = TextEditingController();

  // 媒体选择相关
  AssetEntity? _selectedAsset;
  String? _localMediaPath;
  String? _thumbnailPath;
  PostMediaType _mediaType = PostMediaType.image;

  // 状态管理
  bool _isPublishing = false;

  @override
  void initState() {
    super.initState();
    _qaManager = serviceLocator<ReduxQAManager>();
    _socialManager = serviceLocator<ReduxSocialManager>();
    _userManager = serviceLocator<ReduxUserManager>();
    _tabController = TabController(
      length: 2,
      vsync: this,
      initialIndex: widget.initialTabIndex,
    );
  }

  @override
  void dispose() {
    _tabController.dispose();
    _contentController.dispose();
    _timeController.dispose();
    super.dispose();
  }

  bool _isUserLoggedIn() => _userManager.getCurrentUser() != null;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopNavigationBar(),

              // 主内容区域
              Expanded(
                child: Container(
                  margin: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(16.r),
                  ),
                  child: Column(
                    children: [
                      // Tab栏
                      _buildTabBar(),

                      // Tab内容
                      Expanded(
                        child: TabBarView(
                          controller: _tabController,
                          children: [
                            _buildQAContent(),
                            _buildCommunityContent(),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              // EULA
              Text(
                'EULA',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: const Color(0xFF999999),
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w400,
                  decoration: TextDecoration.underline,
                  decorationColor: const Color(0xFF999999),
                ),
              ).inkWell(
                onTap: () {
                  VamUrl.openEula();
                },
              ),

              // 底部发布按钮
              _buildPublishButton(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          Icon(
            Icons.arrow_back,
            color: Colors.white,
            size: 26.w,
          ).inkWell(onTap: () => Navigator.pop(context)),

          // 标题
          Expanded(
            child:
                Text('CREATE')
                    .fontSize(20.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w700,
                      ).fontFamily!,
                    )
                    .center(),
          ),

          // 占位
          SizedBox(width: 20.w),
        ],
      ),
    );
  }

  /// 构建Tab栏
  Widget _buildTabBar() {
    return Container(
      margin: EdgeInsets.all(16.w),
      child: TabBar(
        controller: _tabController,
        indicatorColor: Colors.white,
        indicatorWeight: 2.h,
        labelColor: Colors.white,
        unselectedLabelColor: Colors.white.withOpacity(0.6),
        labelStyle: GoogleFonts.poppins(
          fontWeight: FontWeight.w600,
          fontSize: 16.sp,
        ),
        unselectedLabelStyle: GoogleFonts.poppins(
          fontWeight: FontWeight.w600,
          fontSize: 16.sp,
        ),
        tabs: const [Tab(text: 'Q&A'), Tab(text: 'Community')],
      ),
    );
  }

  /// 构建问答内容
  Widget _buildQAContent() {
    return Padding(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 文本输入框
          Container(
            width: double.infinity,
            height: 120.h,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: TextField(
              controller: _contentController,
              style: TextStyle(
                color: Colors.black,
                fontSize: 14.sp,
                fontFamily: GoogleFonts.poppins().fontFamily,
              ),
              decoration: InputDecoration(
                hintText: 'Ask a question...',
                hintStyle: TextStyle(color: Colors.grey[500], fontSize: 14.sp),
                border: InputBorder.none,
                contentPadding: EdgeInsets.all(16.w),
              ),
              maxLines: null,
              expands: true,
              textAlignVertical: TextAlignVertical.top,
            ),
          ),

          SizedBox(height: 16.h),

          // 媒体选择按钮
          _buildMediaPickerButton(),

          // 问答不需要选择时间，直接使用点击发布时的时间
        ],
      ),
    );
  }

  /// 构建社区内容
  Widget _buildCommunityContent() {
    return Padding(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 文本输入框
          Container(
            width: double.infinity,
            height: 120.h,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: TextField(
              controller: _contentController,
              style: TextStyle(
                color: Colors.black,
                fontSize: 14.sp,
                fontFamily: GoogleFonts.poppins().fontFamily,
              ),
              decoration: InputDecoration(
                hintText: 'Say Something...',
                hintStyle: TextStyle(color: Colors.grey[500], fontSize: 14.sp),
                border: InputBorder.none,
                contentPadding: EdgeInsets.all(16.w),
              ),
              maxLines: null,
              expands: true,
              textAlignVertical: TextAlignVertical.top,
            ),
          ),

          SizedBox(height: 16.h),

          // 媒体选择按钮
          _buildMediaPickerButton(),

          SizedBox(height: 16.h),

          // 时间选择（可选）
          Container(
            width: double.infinity,
            height: 48.h,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Center(
              child: TextField(
                controller: _timeController,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 14.sp,
                  fontFamily: GoogleFonts.poppins().fontFamily,
                ),
                decoration: InputDecoration(
                  hintText: 'Select Time',
                  hintStyle: TextStyle(
                    color: Colors.grey[500],
                    fontSize: 14.sp,
                  ),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(horizontal: 16.w),
                ),
                readOnly: true,
                onTap: _showTimePicker,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建媒体选择按钮
  Widget _buildMediaPickerButton() {
    return Container(
      width: 80.w,
      height: 80.w,
      decoration: BoxDecoration(
        color: Colors.grey[800],
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.add_a_photo, color: Colors.white, size: 24.w),
          SizedBox(height: 4.h),
          Text(
            _selectedAsset != null ? '1/1' : '0/1',
            style: TextStyle(
              color: Colors.white,
              fontSize: 12.sp,
              fontFamily: GoogleFonts.poppins().fontFamily,
            ),
          ),
        ],
      ),
    ).inkWell(onTap: _pickMedia);
  }

  /// 构建发布按钮
  Widget _buildPublishButton() {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.all(16.w),
      child: Container(
        height: 48.h,
        decoration: ShapeDecoration(
          color: const Color(0xFFF7CEBA),
          shape: RoundedRectangleBorder(
            side: BorderSide(width: 1.w),
            borderRadius: BorderRadius.circular(41.r),
          ),
          shadows: [
            BoxShadow(
              color: Color(0xFF000000),
              blurRadius: 0,
              offset: Offset(4, 4),
              spreadRadius: 0,
            ),
          ],
        ),
        child: Text(
          'PUBLISH',
          style: TextStyle(
            color: Colors.black,
            fontSize: 16.sp,
            fontWeight: FontWeight.w400,
            fontFamily:
                GoogleFonts.protestStrike(
                  fontWeight: FontWeight.w400,
                ).fontFamily,
          ),
        ).center().inkWell(onTap: _isPublishing ? null : _handlePublish),
      ),
    );
  }

  /// 选择媒体
  Future<void> _pickMedia() async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.common,
          specialPickerType: SpecialPickerType.noPreview,
          textDelegate: const AssetPickerTextDelegate(),
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final asset = assets.first;
        setState(() {
          _selectedAsset = asset;
        });

        // 处理选中的媒体
        await _processSelectedAsset(asset);
      }
    } catch (e) {
      NotificationUtils.showError(context, message: 'Failed to pick media: $e');
    }
  }

  /// 处理选中的媒体
  Future<void> _processSelectedAsset(AssetEntity asset) async {
    try {
      // 获取应用文档目录
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String mediaDir = '${appDocDir.path}/media';
      await Directory(mediaDir).create(recursive: true);

      if (asset.type == AssetType.video) {
        // 处理视频
        _mediaType = PostMediaType.video;

        // 复制视频文件
        final String videoPath =
            '$mediaDir/video_${DateTime.now().millisecondsSinceEpoch}.mp4';
        final File? videoFile = await asset.file;
        if (videoFile != null) {
          await videoFile.copy(videoPath);
          _localMediaPath = videoPath;
        }

        // 生成缩略图
        final String thumbnailPath =
            '$mediaDir/thumb_${DateTime.now().millisecondsSinceEpoch}.jpg';
        final String? thumbnail = await VideoThumbnail.thumbnailFile(
          video: videoPath,
          thumbnailPath: thumbnailPath,
          imageFormat: ImageFormat.JPEG,
          maxHeight: 300,
          quality: 75,
        );
        _thumbnailPath = thumbnail;
      } else {
        // 处理图片
        _mediaType = PostMediaType.image;

        // 复制图片文件
        final String imagePath =
            '$mediaDir/image_${DateTime.now().millisecondsSinceEpoch}.jpg';
        final File? imageFile = await asset.file;
        if (imageFile != null) {
          await imageFile.copy(imagePath);
          _localMediaPath = imagePath;
        }
      }

      setState(() {});
    } catch (e) {
      NotificationUtils.showError(
        context,
        message: 'Failed to process media: $e',
      );
    }
  }

  /// 显示时间选择器
  void _showTimePicker() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => _buildTimePickerBottomSheet(),
    );
  }

  /// 构建时间选择底部弹窗
  Widget _buildTimePickerBottomSheet() {
    DateTime now = DateTime.now();
    DateTime selectedDateTime = now;

    return StatefulBuilder(
      builder: (context, setModalState) {
        return ClipRRect(
          borderRadius: BorderRadius.circular(24.r),
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
            child: Container(
              height: 452.h,
              decoration: BoxDecoration(
                color: Colors.white.withValues(alpha: 0.30),
                borderRadius: BorderRadius.circular(24.r),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.3),
                    blurRadius: 10,
                    offset: Offset(0, 5),
                  ),
                ],
              ),
              child: Column(
                children: [
                  // 标题区域
                  Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 10.w,
                      vertical: 16.w,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text(
                          'Choose a time',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 18.sp,
                            fontWeight: FontWeight.w400,
                            fontFamily:
                                GoogleFonts.goblinOne(
                                  fontWeight: FontWeight.w400,
                                ).fontFamily,
                          ),
                        ),
                        SizedBox(height: 8.h),
                        Text(
                          'Please select the time you want to publish',
                          style: TextStyle(
                            color: Colors.grey[400],
                            fontSize: 13.sp,
                            fontFamily: GoogleFonts.inter().fontFamily,
                          ),
                        ),
                      ],
                    ),
                  ),

                  // 时间选择器区域
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.symmetric(horizontal: 16.w),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(18.r)),
                      ),
                      child: Row(
                        children: [
                          // 年份选择
                          Expanded(
                            child: _buildTimePickerColumn(
                              items: List.generate(
                                5,
                                (index) => now.year + index,
                              ),
                              selectedValue: selectedDateTime.year,
                              onChanged: (value) {
                                setModalState(() {
                                  final newDateTime = DateTime(
                                    value,
                                    selectedDateTime.month,
                                    selectedDateTime.day,
                                    selectedDateTime.hour,
                                    selectedDateTime.minute,
                                  );
                                  // 确保选择的时间不早于当前时间
                                  selectedDateTime =
                                      newDateTime.isBefore(now)
                                          ? now
                                          : newDateTime;
                                });
                              },
                            ),
                          ),

                          // 小时选择
                          Expanded(
                            child: _buildTimePickerColumn(
                              items: List.generate(24, (index) => index),
                              selectedValue: selectedDateTime.hour,
                              onChanged: (value) {
                                setModalState(() {
                                  final newDateTime = DateTime(
                                    selectedDateTime.year,
                                    selectedDateTime.month,
                                    selectedDateTime.day,
                                    value,
                                    selectedDateTime.minute,
                                  );
                                  // 确保选择的时间不早于当前时间
                                  selectedDateTime =
                                      newDateTime.isBefore(now)
                                          ? now
                                          : newDateTime;
                                });
                              },
                            ),
                          ),

                          // 分钟选择
                          Expanded(
                            child: _buildTimePickerColumn(
                              items: List.generate(60, (index) => index),
                              selectedValue: selectedDateTime.minute,
                              onChanged: (value) {
                                setModalState(() {
                                  final newDateTime = DateTime(
                                    selectedDateTime.year,
                                    selectedDateTime.month,
                                    selectedDateTime.day,
                                    selectedDateTime.hour,
                                    value,
                                  );
                                  // 确保选择的时间不早于当前时间
                                  selectedDateTime =
                                      newDateTime.isBefore(now)
                                          ? now
                                          : newDateTime;
                                });
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),

                  // 确认按钮
                  Container(
                    width: double.infinity,
                    margin: EdgeInsets.all(16.w),
                    child: Container(
                      height: 48.h,
                      decoration: ShapeDecoration(
                        color: const Color(0xFFF7CEBA),
                        shape: RoundedRectangleBorder(
                          side: BorderSide(width: 1.w),
                          borderRadius: BorderRadius.circular(41.r),
                        ),
                        shadows: [
                          BoxShadow(
                            color: Color(0xFF000000),
                            blurRadius: 0,
                            offset: Offset(4, 4),
                            spreadRadius: 0,
                          ),
                        ],
                      ),
                      child: Text(
                        'CONFIRMATION TIME',
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 20.sp,
                          fontWeight: FontWeight.w400,
                          fontFamily:
                              GoogleFonts.protestStrike(
                                fontWeight: FontWeight.w400,
                              ).fontFamily,
                        ),
                      ).center().inkWell(
                        onTap: () {
                          _timeController.text =
                              '${selectedDateTime.year}-${selectedDateTime.month.toString().padLeft(2, '0')}-${selectedDateTime.day.toString().padLeft(2, '0')} ${selectedDateTime.hour.toString().padLeft(2, '0')}:${selectedDateTime.minute.toString().padLeft(2, '0')}';
                          Navigator.pop(context);
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建时间选择器列
  Widget _buildTimePickerColumn({
    required List<int> items,
    required int selectedValue,
    required ValueChanged<int> onChanged,
  }) {
    final initialIndex = items
        .indexOf(selectedValue)
        .clamp(0, items.length - 1);
    final controller = FixedExtentScrollController(initialItem: initialIndex);

    return Container(
      height: double.infinity,
      child: ListWheelScrollView.useDelegate(
        controller: controller,
        itemExtent: 50.h,
        physics: const FixedExtentScrollPhysics(),
        perspective: 0.003,
        diameterRatio: 2.5,
        onSelectedItemChanged: (index) {
          if (index >= 0 && index < items.length) {
            onChanged(items[index]);
          }
        },
        childDelegate: ListWheelChildBuilderDelegate(
          builder: (context, index) {
            if (index < 0 || index >= items.length) return null;
            final item = items[index];
            final isSelected = item == selectedValue;
            return Center(
              child: Text(
                item.toString().padLeft(2, '0'),
                style: TextStyle(
                  color: isSelected ? Colors.black : Colors.grey[500],
                  fontSize: isSelected ? 18.sp : 16.sp,
                  fontWeight: isSelected ? FontWeight.w700 : FontWeight.w400,
                  fontFamily: GoogleFonts.poppins().fontFamily,
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  /// 处理发布
  Future<void> _handlePublish() async {
    // 检查用户是否登录
    if (!_isUserLoggedIn()) {
      VamosLoginRequiredDialog.showLoginRequiredDialog(context);
      return;
    }

    final currentUser = _userManager.getCurrentUser();
    if (currentUser == null) return;

    // 检查内容
    final content = _contentController.text.trim();
    if (content.isEmpty) {
      NotificationUtils.showError(context, message: 'Please enter content');
      return;
    }

    setState(() {
      _isPublishing = true;
    });

    try {
      final isQA = _tabController.index == 0;

      if (isQA) {
        // 发布问答
        await _publishQuestion(currentUser.uniqueId, content);
      } else {
        // 发布社交动态
        await _publishSocialPost(currentUser.uniqueId, content);
      }

      // 发布成功
      NotificationUtils.showSuccess(
        context,
        message: 'Published successfully!',
      );
      Navigator.pop(context);
    } catch (e) {
      NotificationUtils.showError(context, message: 'Failed to publish: $e');
    } finally {
      setState(() {
        _isPublishing = false;
      });
    }
  }

  /// 发布问答
  Future<void> _publishQuestion(String userId, String content) async {
    final question = QuestionEntity(
      questionId: 'question_${DateTime.now().millisecondsSinceEpoch}',
      authorId: userId,
      title: content,
      mediaType:
          _mediaType == PostMediaType.video
              ? QAMediaType.video
              : QAMediaType.image,
      mediaUrl: _localMediaPath,
      thumbnailUrl: _thumbnailPath,
      publishTime: DateTime.now(),
      likeCount: 0,
      answerCount: 0,
      likedUserIds: [],
    );

    final success = await _qaManager.publishQuestion(question);
    if (!success) {
      throw Exception('Failed to publish question');
    }
  }

  /// 发布社交动态
  Future<void> _publishSocialPost(String userId, String content) async {
    final post = SocialPostEntity(
      postId: 'post_${DateTime.now().millisecondsSinceEpoch}',
      authorId: userId,
      content: content,
      mediaType: _mediaType,
      mediaUrl: _localMediaPath,
      thumbnailUrl: _thumbnailPath,
      publishTime: DateTime.now(),
      likeCount: 0,
      commentCount: 0,
      likedUserIds: [],
    );

    final success = await _socialManager.publishPost(post);
    if (!success) {
      throw Exception('Failed to publish post');
    }
  }
}
